package com.runshu.newsmartark.activity;

import android.Manifest;
import android.app.ZysjSystemManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSON;
import com.arialyy.aria.core.Aria;
import com.runshu.newsmartark.R;
import com.runshu.newsmartark.base.BoxBaseActivity;
import com.runshu.newsmartark.base.MyApplication;
import com.runshu.newsmartark.dbutil.RefreshUtils;
import com.runshu.newsmartark.entity.HwInfoUtils;
import com.runshu.newsmartark.entity.MqttBean;
import com.runshu.newsmartark.mvp.contract.GetVersionContract;
import com.runshu.newsmartark.mvp.contract.MainHomeContract;
import com.runshu.newsmartark.mvp.model.GetVersionModel;
import com.runshu.newsmartark.mvp.model.HwHeartModel;
import com.runshu.newsmartark.mvp.model.MainHomeModel;
import com.runshu.newsmartark.mvp.presenter.GetVersionPresenter;
import com.runshu.newsmartark.mvp.presenter.HwHeartPresenter;
import com.runshu.newsmartark.mvp.presenter.MainHomePresenter;
import com.runshu.newsmartark.network.netbean.ResponseBean;
import com.runshu.newsmartark.networkstate.annotation.NetworkSubscribe;
import com.runshu.newsmartark.networkstate.type.NetFilterType;
import com.runshu.newsmartark.networkstate.type.NetType;
import com.runshu.newsmartark.service.SyncDataService;
import com.runshu.newsmartark.util.MQTTManager;
import com.runshu.newsmartark.util.MacUtils;
import com.runshu.newsmartark.util.NetStatusUtils;
import com.runshu.newsmartark.util.RefUtil;
import com.runshu.newsmartark.util.SoundPoolUtils;
import com.runshu.newsmartark.util.StringUtils;
import com.runshu.newsmartark.util.common.LogUtil;
import com.runshu.newsmartark.util.common.SharedPreferencesUtils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import cn.wch.ch34xuartdriver.CH34xUARTDriver;

import static com.runshu.newsmartark.common.ConstantUrl.HEART_BEAT_IOT;
import static com.runshu.newsmartark.common.ConstantUrl.Share_isAdmin;
import static com.runshu.newsmartark.util.MQTTManager.PUB_TOPIC;
import static com.runshu.newsmartark.util.MQTTManager.SUB_TOPIC;

/**
 * Demo class
 *
 * @author yu
 * @date 2021/12/28
 * @decs：
 */

public class NewMainactivity extends BoxBaseActivity implements ViewTreeObserver.OnGlobalLayoutListener, MainHomeContract.View, GetVersionContract.View{
    private static final String TAG = "NewMainactivity";
    private final String macAddress = MacUtils.getFormatMacAddr();  //"EA06GC27A573";
    private MainHomePresenter homePresenter;
    private static final String ACTION_USB_PERMISSION = "cn.wch.wchusbdriver.USB_PERMISSION";

    ZysjSystemManager mManager = null;

    /**
     * 所需的所有权限信息
     */
    private static final String[] NEEDED_PERMISSIONS = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.READ_PHONE_STATE,
            ACTION_USB_PERMISSION

    };

    private static final int ACTION_REQUEST_PERMISSIONS = 0x001;
    private LocalBroadcastManager lbm;
    //温控
    private int retval;
    public boolean isOpen = false;
    private MyHandler wenkHandler;

    public int time = 1000 * 60 * 30;
    MQTTManager mqttManager;

    public static int dckmsj = 1;
    public static int[] dckmsjTime = {1000 * 60 * 5, 1000 * 60 * 30, 1000 * 60 * 60, 1000 * 60 * 60 * 3};
    final String[] dckmhint = {"5分钟", "30分钟", "1小时", "3小时"};


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Aria.get(this).getDownloadConfig().setMaxTaskNum(1);
        Aria.download(this).register();
        //你也可以在这里初始化，对当前页面网络实时监听
        RefreshUtils.getInstance();
        UsbManager();
        if (!isOpen) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    UsbManager();
                }
            }, 3000); // 延时3秒
        }
        BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                    Toast.makeText(getApplicationContext(), "USB已移除", Toast.LENGTH_SHORT).show();
                    isOpen = false;

                } else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                    Toast.makeText(getApplicationContext(), "USB已连接", Toast.LENGTH_SHORT).show();
                    UsbManager();

                    if (!isOpen) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                UsbManager();
                            }
                        }, 3000); // 延时3秒
                    }
                }
            }
        };

        IntentFilter usbDeviceStateFilter = new IntentFilter();
        usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        registerReceiver(mUsbReceiver, usbDeviceStateFilter);

    }

    @Override
    public void onGlobalLayout() {
        if (!checkPermissions(NEEDED_PERMISSIONS)) {
            ActivityCompat.requestPermissions(this, NEEDED_PERMISSIONS, ACTION_REQUEST_PERMISSIONS);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.act_new_main;
    }

    @Override
    protected void initView() {
        lbm = LocalBroadcastManager.getInstance(this);
        homePresenter = new MainHomePresenter(this, new MainHomeModel());
    }

    @Override
    protected void initData() {
        PUB_TOPIC = "hw/" + HwInfoUtils.getCustomerId(context) + "/" + HwInfoUtils.getHospitalId(context) + "/" + MacUtils.getFormatMacAddr();
        SUB_TOPIC = "iot/" + HwInfoUtils.getCustomerId(context) + "/" + HwInfoUtils.getHospitalId(context) + "/" + MacUtils.getFormatMacAddr();
        MQTTManager mqttManager = MQTTManager.getInstance(context);
        assert mqttManager != null;
        mqttManager.connect();
        //没联网弹框
        if (!NetStatusUtils.isConnected(context)) {
            SoundPoolUtils.play(context, R.raw.raw_net_erro, 0);
        }
        exitLogin();
    }

    @Override
    protected void bindListener() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        startService(new Intent(NewMainactivity.this, SyncDataService.class));
        homePresenter.getHdInfo(macAddress);

        //同步接口数据（医院信息， 基本信息 ====）
        new Thread(new Runnable() {
            @Override
            public void run() {
                RefreshUtils.getInstance().refreshAll();

            }
        }).start();

        homePresenter.getInventorySum(HwInfoUtils.getCustomerId(context), HwInfoUtils.getHospitalId(context), macAddress);
    }

    @Override
    protected void afterRequestPermission(int requestCode, boolean isAllGranted) {
        if (!checkPermissions(NEEDED_PERMISSIONS)) {
            ActivityCompat.requestPermissions(this, NEEDED_PERMISSIONS, ACTION_REQUEST_PERMISSIONS);
        }
    }

    @Override
    public void OnGetVersionInfoSuccess(ResponseBean responseBean) {

    }

    @Override
    public void getIndexCount(ResponseBean responseBean) {

    }

    @Override
    public void getHdInfoSuccess(ResponseBean responseBean) {

    }

    @Override
    public void getInventorySumSuccess(ResponseBean responseBean) {

    }

    @Override
    public void onScanSuccess(String barcode) {
        scanToOpenDoor(barcode, false);
    }

    @NetworkSubscribe(netFilterType = NetFilterType.ALL)
    public void netWorkChangeCallBack(NetType netType) {
        switch (netType) {
            case MOBILE:
                Log.e("NewMainactivity", "NewMainactivity 已连接移动网络");
            case WIFI:
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            RefreshUtils.getInstance().insertHardwareLog(null);
                            Thread.sleep(3000); // 休眠3秒
                            MQTTManager mqttManager = MQTTManager.getInstance(context);
                            assert mqttManager != null;
                            mqttManager.subscribeMsg(SUB_TOPIC, 0);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                }).start();
                Log.e("NewMainactivity", "NewMainactivity 已连接到wifi");
                break;
            case NONE:
                Log.e("NewMainactivity", "NewMainactivity 网络断开");
                break;
            default:
                break;
        }
    }
    public void UsbManager() {
        wenkHandler = new MyHandler(NewMainactivity.this);
        MyApplication.driver = new CH34xUARTDriver(
                (UsbManager) getSystemService(Context.USB_SERVICE), this,
                ACTION_USB_PERMISSION);
        if (!MyApplication.driver.isConnected()) {


            if (!isOpen) {
                int retval = MyApplication.driver.ResumeUsbPermission();
                if (retval == 0) {
                    //Resume usb device list
                    retval = MyApplication.driver.ResumeUsbList();
                    if (retval == -1)// ResumeUsbList方法用于枚举CH34X设备以及打开相关设备
                    {
                        Toast.makeText(NewMainactivity.this, "Open failed!",
                                Toast.LENGTH_SHORT).show();
                        MyApplication.driver.CloseDevice();
                    } else if (retval == 0) {
                        if (MyApplication.driver.mDeviceConnection != null) {
                            if (!MyApplication.driver.UartInit()) {//对串口设备进行初始化操作
                                Toast.makeText(NewMainactivity.this, "Initialization failed!",
                                        Toast.LENGTH_SHORT).show();
                                return;
                            }
                            Toast.makeText(NewMainactivity.this, "Device opened",
                                    Toast.LENGTH_SHORT).show();
                            isOpen = true;
                            new NewMainactivity.ReadThread().start();//开启读线程读取串口接收的数据
                            //配置串口波特率，函数说明可参照编程手册
                            MyApplication.driver.SetConfig(9600, Byte.parseByte("8"), Byte.parseByte("1"), Byte.parseByte("0"), Byte.parseByte("0"));


                        } else {
                            Toast.makeText(NewMainactivity.this, "Open failed!",
                                    Toast.LENGTH_SHORT).show();
                        }
                    } else {

                        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
                        builder.setTitle("未授权限");
                        builder.setMessage("确认退出吗？");
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                System.exit(0);
                            }
                        });
                        builder.setNegativeButton("返回", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub

                            }
                        });
                        builder.show();

                    }
                } else {
                    isOpen = false;
                    MyApplication.driver.CloseDevice();
                }
            } else {
                isOpen = false;
                MyApplication.driver.CloseDevice();
            }
        }
    }

    MqttBean mqttBean = new MqttBean();


    private class ReadThread extends Thread {
        @Override
        public void run() {
            byte[] buffer = new byte[4096];
            while (true) {
                try {
                    MyApplication.driver.ReadData(buffer, 4096);
                    Thread.sleep(1000 * 60 * 5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message msg = Message.obtain();
                if (!isOpen) {
                    break;
                }
                int length = MyApplication.driver.ReadData(buffer, 4096);
                if (length > 0) {
                    String recv = new String(buffer, 0, length);
                    msg.obj = recv;
                    wenkHandler.sendMessage(msg);
                }
            }
        }
    }

    private static class MyHandler extends Handler {
        WeakReference<NewMainactivity> mainActivityWeakReference;

        MyHandler(NewMainactivity activity) {
            mainActivityWeakReference = new WeakReference<NewMainactivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            NewMainactivity activity = mainActivityWeakReference.get();
            if (activity != null) {
                String wenshiInfo = msg.obj.toString();
                LogUtil.e("温控==", msg.obj.toString());
                if (wenshiInfo.startsWith("T")) {
                    String[] split1 = wenshiInfo.split("\r\n");

                    if (split1.length >= 2) {
                        String[] split = split1[0].split(",");
                        if (split.length == 2) {
                            String wendu = split[0].replace("T:", "");
                            String shidu = split[1].replace("RH:", "");
                            LogUtil.e("x", "wendu==" + wendu + "===" + "shidu===" + shidu);
                            activity.sendTemperature(String.format("%.1f", Double.parseDouble(wendu)), String.valueOf((int) (Double.parseDouble(shidu) * 100)));
                        }


                    }
                }
            }
        }
    }

    MqttBean.HeaderBean headerBean = new MqttBean.HeaderBean();
    MqttBean.BodyBean mqttBeanBodyTemperature = new MqttBean.BodyBean();

    public void sendTemperature(String wendu, String shidu) {
        MQTTManager mqttManager = MQTTManager.getInstance(context);
        assert mqttManager != null;
        headerBean.setCommand(HEART_BEAT_IOT);
        headerBean.setCustomerId(HwInfoUtils.getCustomerId(context));
        headerBean.setHospitalId(HwInfoUtils.getHospitalId(context));
        headerBean.setMac(MacUtils.getFormatMacAddr());
        headerBean.setResultCode(0);
        mqttBeanBodyTemperature.setTemperature(wendu);
        mqttBeanBodyTemperature.setHumidity(shidu);
        mqttBean.setHeader(headerBean);
        mqttBean.setBody(mqttBeanBodyTemperature);
        mqttManager.publish(PUB_TOPIC, JSON.toJSONString(mqttBean), false, 0);

    }
    ArrayList<String> str = new ArrayList<>();
    MqttBean.BodyBean mqttBeanBody = new MqttBean.BodyBean();
    @Override
    public void onScanResult(List<HashMap<String, String>> lsTagList, long a, long b) {
        super.onScanResult(lsTagList, a, b);
            if (str == null) str = new ArrayList<>();
            str.clear();
            for (int i = 0; i < lsTagList.size(); i++) {
                str.add(RefUtil.decryptRfid(lsTagList.get(i).get("epc").replace(" ", "")));
            }

            MQTTManager mqttManager = MQTTManager.getInstance(context);
            assert mqttManager != null;
            mqttBeanBody.setCommCode(1);
            mqttBeanBody.setConsumablesNum(lsTagList.size());
            mqttBeanBody.setRfidsList(str);
            mqttBean.setBody(mqttBeanBody);
            mqttManager.publish(PUB_TOPIC, JSON.toJSONString(mqttBean), false, 0);

    }

}